Date.prototype.formatDateDef = function (format) {
    if (isNaN(this)) {
        return '';
    }
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}//grid转换日期格式
function ieFlag(value, indx, rowObj) {
    if ('I' == value) {
        return '进口';
    } else if ('E' == value) {
        return '出口';
    }
    return '';
}
function tradeMode(value, indx, rowObj) {
    if ('0' == value) {
        return '一般贸易';
    } else if ('1' == value) {
        return '保税';
    }
    return '';
}
function returnFlag(value, indx, rowObj) {
    if ('0' == value) {
        return '正常';
    } else if ('1' == value) {
        return '退货';
    }
    return '';
}
function formatDate(value, indx, rowObj) {
    if (null == value) {
        return '';
    }
    return new Date(value).formatDateDef('yyyy-MM-dd');
}
function formatTime(value, indx, rowObj) {
    if (null == value) {
        return '';
    }
    return new Date(value).formatDateDef('yyyy-MM-dd hh:mm:ss');
}
/*将url参数回填绑定给对应table 比如 SearcheTable*/
function setTableByUrl(table) {
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strArr = new Array();
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            var name = strs[i].split("=")[0];
            var val = strs[i].split("=")[1];
            strArr[i] = "\"" + name + "\":\"" + UrlDecode(val) + "\"";
        }
        var strJson = strArr.join(",");
        strJson = "{\"" + table.toUpperCase() + "\":[{" + strJson + "}]}";
        var datasource = eval("(" + strJson + ")");
        FormBind(datasource);
        return strJson;
    }
}

/*---UrlDecode-------*/
function UrlDecode(zipStr) {
    var uzipStr = "";
    for (var i = 0; i < zipStr.length; i++) {
        var chr = zipStr.charAt(i);
        if (chr == "+") {
            uzipStr += " ";
        } else if (chr == "%") {
            var asc = zipStr.substring(i + 1, i + 3);
            if (parseInt("0x" + asc) > 0x7f) {
                uzipStr += decodeURI("%" + asc.toString() + zipStr.substring(i + 3, i + 9).toString());
                i += 8;
            } else {
                uzipStr += AsciiToString(parseInt("0x" + asc));
                i += 2;
            }
        } else {
            uzipStr += chr;
        }
    }

    return uzipStr;
}

function StringToAscii(str) {
    return str.charCodeAt(0).toString(16);
}
function AsciiToString(asccode) {
    return String.fromCharCode(asccode);
}
function search(gridId, url) {
    var data = customFormToData("SearchTable");
    $("#" + gridId).jqGrid('setGridParam', {
        url: url, postData: JSON.parse(data), page: 1
    }).trigger("reloadGrid");
}

function rowDetail(url, cellvalue) {
    cellvalue = cellvalue == null ? "" : cellvalue;
    cellvalue = $.trim(cellvalue);
    return "<a href=\"#detail\" onclick=\"location.href='" + url + "'\">" + cellvalue + "</a>";
}

function disablePage(type) {

    var option = $('#type', parent.document).val();
    var custStatus = $('#declareCustStatusHidden', parent.document).val();
    var inspStatus = $('#declareInspStatusHidden', parent.document).val();

    var custEditable = custStatus == "0" || custStatus == "";
    var inspEditable = inspStatus == "0" || inspStatus == "";

    if (!custEditable && !inspEditable) {
        option = 'detail';
    }

    if (option == 'detail') {
        $(":text,select,textarea,button").attr("disabled", "disabled");
        $("a").attr("disabled", "disabled").attr("href", 'javascript:void(0)').unbind('click');
        return;
    }

    if (!custEditable) {
        var clazz = type == 'cust' ? 'titleCss' : 'redtitleCss';

        $("td[class^='" + clazz + "']").closest("div").find(":text,select,textarea").attr("disabled", "disabled");
        $("td[class^='" + clazz + "']").closest("div").find("a").attr("disabled", "disabled").attr("href",
            'javascript:void(0)').unbind('click');
        return;
    }

    if (!inspEditable) {
        var clazz = type == 'cust' ? 'titleCss' : 'bluetitleCss';

        $("td[class^='" + clazz + "']").closest("div").find(":text,select,textarea").attr("disabled", "disabled");
        $("td[class^='" + clazz + "']").closest("div").find("a").attr("disabled", "disabled").attr("href",
            'javascript:void(0)').unbind('click');

        return;
    }
}

function resetForm(formId) {
    $(':input', "#" + formId).not(':button, :submit, :reset').val('').removeAttr('checked').removeAttr('selected');
}

function openTab(url, title) {
    index = layer.open({
        title: title,
        area: [$(window).width() * 0.8 + 'px', $(window).height() * 0.8 + 'px'],
        offset: '100px',
        type: 2,
        scrollbar: false,
        content: url
    });
}

function openInspStatus() {
    layer.open({
        type: 2,
        title: false,
        shadeClose: true,
        area: ['880px', '50%'],
        content: $basePath + '/status/init?declNo=' + $("#declNo").val() + '&statusProcess=' + $("#declareInspStatusHidden").val()
    });
}
function openCustStatus() {
    layer.open({
        type: 2,
        title: false,
        shadeClose: true,
        area: ['880px', '50%'],
        content: $basePath + '/status/toCustStatusPage?declNo=' + $("#sheetNo").val()
    });
}
var index = "";
function getModelC(val) {
    var hsCodeZ = $("#hscode").val();
    if ("" == hsCodeZ) {
        layer.tips('请先填写HS编码', '#hscode_input', {
            tips: [1, '#b94a48'] //还可配置颜色
        });
        $("#hscode_input").focus();
        return false;
    }

    layer.open({
        type: 2,
        title: false,
        shadeClose: true,
        area: ['80%', '80%'],
        content: $basePath + '/chooseModel/choose?hsCodeZ=' + hsCodeZ + '&thisVal=' + val
    });

}
var _split = "------===";
function getGoodsNo(relateKey) {
    var aaaa = $("#" + relateKey).tautocomplete({
        relateKey: relateKey,
        placeholder: "请输入关键字",
        width: "600px",
        isCheck: true,
        regex: "^[a-zA-Z0-9\\s]+$",
        columns: ['商品序号', '商品中文名称', '商品英文名称'],
        ajax: {
            url: $basePath + "/cache/getGoodsNo", dataType: "json", type: "post", data: function () {
                return {
                    featureClass: "P",
                    style: "full",
                    maxRows: 11,
                    declNo: $("#declNo", parent.document).val(),
                    name_startsWith: aaaa.searchdata()
                };
            }, success: function (jsonData) {
                if (jsonData) {
                    var filterData = [];
                    $.each(jsonData, function (i, item) {
                        var obj = {
                            id: item.GOODS_NO,
                            GOODS_NO: item.GOODS_NO,
                            GOODS_CNAME: item.GOODS_CNAME,
                            GOODS_ENAME: item.GOODS_ENAME
                        };
                        filterData.push(obj);
                    });
                    return filterData;
                } else {
                    alert("请先填写表头和货物信息！");
                }
            }
        },
        onchange: function () {
            $("#" + relateKey).val(aaaa.id());

            return;
        }
    });
}
function getConsigneeCodeI(consigneeCodeI) {
    var aaaa = $("#" + consigneeCodeI).tautocomplete({
        relateKey: consigneeCodeI,
        placeholder: "请输入关键字",
        width: "800px",
        isCheck: false,
        regex: "^[a-zA-Z0-9\\s]+$",
        columns: ['收货人编号', '收货人名称', '收货人英文名称'],
        ajax: {
            url: $basePath + "/cache/getConsigneeCodeI", dataType: "json", type: "post", data: function () {
                return {
                    featureClass: "P", style: "full", maxRows: 11, name_startsWith: aaaa.searchdata()
                };
            }, success: function (jsonData) {
                var filterData = [];
                $.each(jsonData, function (i, item) {
                    var obj = {
                        id: item.CONSIGNEE_CODE_I + _split + item.CONSIGNEE_CNAME_I + _split + item.CONSIGNEE_ENAME_I,
                        CONSIGNEE_CODE_I: item.CONSIGNEE_CODE_I,
                        CONSIGNEE_CNAME_I: item.CONSIGNEE_CNAME_I,
                        CONSIGNEE_ENAME_I: item.CONSIGNEE_ENAME_I
                    };
                    filterData.push(obj);
                });
                return filterData;
            }
        },
        onchange: function () {
            var datas = aaaa.id().split(_split);
            var code_t = datas[0] || '';
            var cName = datas[1] || '';
            var eName = datas[2] || '';
            $("#" + consigneeCodeI).val(code_t);
            $("#consigneeCnameI").val(cName);
            $("#consigneeEnameI").val(eName);
            return;
        },
        setUserDefined: function () {
            $("#" + consigneeCodeI).val($("#" + consigneeCodeI + "_input").val());
        }
    });
}
function initHsCode(hsCodeZ) {
    var decType = "1";

    getCargoHsCode({"id": "cargotaxco", "decType": decType});
    $("#cargotaxco_input").val(hsCodeZ);


}

/**
 * @param param
 *        {
 *        "id":'hsCodeZ',
 *        "decType":'2',
 *        "columns":['商品编码', '商品名称'],
 *        "width":'400px',
 *        "onchange":function(el, key, value){
 *
 *                   }
 *        }
 */
function getCargoHsCode(param) {
    var hsCodeId = param["id"];
    var decType = param["decType"];
    var columns = param["columns"] || function () {
            switch (decType) {
                case "0":
                    // 报检
                    return ['商品编码', '商品名称', '监管条件'];
                case "1":
                    // 报关
                    return ['商品编码', '商品名称', '附加编码', '法定单位', '第二单位'];
                case "2":
                    // 综合
                    return ['商品编码', '商品名称', '附加编码', '法定单位', '第二单位', '监管条件'];
                default :
                    return ['商品编码', '商品名称', '附加编码', '法定单位', '第二单位', '监管条件'];
            }

        }();

    var width = param["width"] || "800px";
    var callback = param["onchange"];

    var aaaa = $("#" + hsCodeId).tautocomplete({
        relateKey: hsCodeId,
        placeholder: "请输入关键字",
        css: 'input1',
        width: width,
        columns: columns,
        regex: "^[a-zA-Z0-9\\s]+$",
        ajax: {
            //url: $basePath + "/cache/getCustHSCodeItems",
            url: $basePath + "/cache/getHSCode", dataType: "json", type: "post", data: function () {
                return {
                    featureClass: "P", style: "full", maxRows: 11, decType: decType, name_startsWith: aaaa.searchdata()
                };
            }, success: function (jsonData) {
                var filterData = [];
                $.each(jsonData, function (i, item) {
                    var obj = {};
                    // 报关
                    if ('2' == decType || '1' == decType) {
                        obj = {
                            id: item.CODE_T + _split + item.G_NAME + _split + item.CODE_S + _split + item.INSP_MONITOR_COND +
                            _split + item.LEGALUN + _split + item.LEGALUNCN + _split + item.SECONDUN
                            + _split + item.SECONDUNCN + _split + item.CODE_TS,

                            CODE_T: item.CODE_TS,
                            G_NAME: item.G_NAME,
                            CODE_S: item.CODE_S,
                            LEGALUNCN: item.LEGALUNCN,
                            SECONDUNCN: item.SECONDUNCN,
                            INSP_MONITOR_COND: item.INSP_MONITOR_COND
                        };
                    }
                    // 报检
                    if ('0' == decType) {
                        obj = {
                            id: item.HS_CODE + _split + item.HS_CNAME + _split + item.INSP_MONITOR_COND,

                            CODE_T: item.HS_CODE, G_NAME: item.HS_CNAME, INSP_MONITOR_COND: item.INSP_MONITOR_COND
                        };
                    }

                    filterData.push(obj);
                });

                return filterData;
            }
        },
        onchange: function () {
            var datas = aaaa.id().split(_split);

            var code_t = datas[0] || '';
            var g_name = datas[1] || '';

            $("#" + hsCodeId).val(code_t);

            if (typeof callback == 'function') {
                callback(aaaa, code_t, g_name);
                return;
            }

            $("#cargocn").val(g_name);

            if ("0" == decType) {
                var insp_monitor_cond = datas[2] || '';
                $("#declStatusI").val(insp_monitor_cond);
            } else {
                var code_s = datas[2] || '';
                var insp_monitor_cond = datas[3] || '';
                var legalun = datas[4] || '';
                var legaluncn = datas[5] || '';
                var secondun = datas[6] || '';
                var seconduncn = datas[7] || '';

                // 附件编码
                $("#codeS").val(code_s);
                // 法定单位
                $("#legalun").val(legalun);
                $("#legaluncn").val(legaluncn);
                $("#legaluncn_input").data("text",
                    legaluncn).val((legalun == "" && legaluncn == "") ? "" : (legalun + "/" + legaluncn));
                // 第二单位
                $("#secondun").val(secondun);
                $("#seconduncn").val(seconduncn);
                $("#seconduncn_input").data("text",
                    seconduncn).val((secondun == "" && seconduncn == "") ? "" : (secondun + "/" + seconduncn));

                $("#declStatusI").val(insp_monitor_cond);
            }

            return;
        }
    });
}

function changeValue(id, idArray) {

    var val = $(id).val();

    for (var i in idArray) {
        $("#" + idArray[i]).val(val);
    }
}

function getStatus(code) {
    var status;
    switch (code) {
        case '0':
            status = '本地暂存';
            break;
        case '1':
            status = '已上传';
            break;
        default:
            status = '暂无';
            break;
    }

    return status;
}

/**
 * 查看按钮事件
 * @param type 0查看报检，1查看报关，2综合查看
 */
function toggleShow(type) {
    var cust = {
        showIframe: ["tab_title_4"],
        hideIframe: ["tab_title_5", "tab_title_6", "tab_title_7", "tab_title_8", "tab_title_9"],
        insp: false,
        cust: true
    }

    var insp = {
        showIframe: ["tab_title_5", "tab_title_6", "tab_title_7", "tab_title_8", "tab_title_9"],
        hideIframe: ["tab_title_4"],
        insp: true,
        cust: false
    }

    var all = {
        showIframe: ["tab_title_4", "tab_title_5", "tab_title_6", "tab_title_7", "tab_title_8", "tab_title_9"],
        hideIframe: [],
        insp: true,
        cust: true
    }

    var params;
    switch (type) {
        case 0:
            params = insp;
            break;
        case 1:
            params = cust;
            break;
        case 2:
            params = all;
            break;
        default:
            params = all;
            break;
    }

    if (params.hideIframe) {
        for (var i in params.hideIframe) {
            $("#" + params.hideIframe[i]).css('display', 'none');
        }
    }

    if (params.showIframe) {
        for (var i in params.showIframe) {
            $("#" + params.showIframe[i]).css('display', '');
        }
    }

    $("iframe").each(function (i, elements) {
        //
        //if (elements.contentWindow._validator) {
        //    elements.contentWindow._validator.form();
        //}

        if (params.cust && params.insp) {
            if ((this.name != 'containers' && this.name != 'goods') || !$(elements).contents().find('#radio_all')[0].disabled) {
                showAll($(elements));
            }
        } else if (params.cust) {
            if ((this.name != 'containers' && this.name != 'goods') || !$(elements).contents().find('#radio_cust')[0].disabled) {
                showCust($(elements));
            }
        } else if (params.insp) {
            if ((this.name != 'containers' && this.name != 'goods') || !$(elements).contents().find('#radio_insp')[0].disabled) {
                showInsp($(elements));
            }
        }

        $(elements).contents().find("div[class='span12 box-content']").each(function (i, ele) {

            var child_div = $(ele).children(":visible");
            var parent_div = $(ele).parent();
            if (child_div.length == 0 && parent_div.is(":visible")) {
                parent_div.hide();
            } else if (!parent_div.is(":visible")) {
                parent_div.show();
            }

        });

    });

    $("#tab_title_1").tab("show");

}

function showInsp(elements) {
    elements = elements || $(document.body);
    var contents = elements.contents();
    contents.find("td[class^='bluetitleCss']").closest("div").show().find("input").attr("ignore-data", 'false');

    contents.find("td[class^='redtitleCss']").closest("div").hide().find("input").attr("ignore-data", 'true');

    contents.find("input[custInspFlag='C']").closest("td").hide().find("input").attr("ignore-data", 'true');

    contents.find("input[custInspFlag='I']").closest("td").show().find("input").attr("ignore-data",
        'false').closest("table").find("td:first").each(function () {
        if ($(this).attr("data-all")) {
            $(this).html(($(this).attr("data-all") || "").split("/")[1]);
        }

    });

    var _div = contents.find("input[custInspFlag='I']").closest("table").closest("div");
    _div.each(function () {
        if ($(this).hasClass("span8")) {
            $(this).removeClass("span8").addClass("span4");
        }

        if ($(this).hasClass("span6")) {
            $(this).removeClass("span6").addClass("span3");
        }
    });

    contents.find('[name="decType"]').each(function () {
        if (this.id == 'radio_insp') {
            this.click();
            return;
        }
    });

    $("div[name*='needMove']").each(function () {
        var id = $(this).attr("id");
        $("#" + id).appendTo("#" + id + "Insp");
    });
}

function showCust(elements) {
    $("div[name*='needMove']").each(function () {
        var id = $(this).attr("id");
        $("#" + id).appendTo("#" + id + "Cust");
    });
    elements = elements || $(document.body);
    var contents = elements.contents();
    contents.find("td[class^='redtitleCss']").closest("div").show().find("input").attr("ignore-data", 'false');

    contents.find("td[class^='bluetitleCss']").closest("div").hide().find("input").attr("ignore-data", 'true');

    contents.find("input[custInspFlag='C']").closest("td").show().find("input").attr("ignore-data",
        'false').closest("table").find("td:first").each(function () {
        if ($(this).attr("data-all")) {
            $(this).html(($(this).attr("data-all") || "").split("/")[0]);
        }
    });
    contents.find("input[custInspFlag='I']").closest("td").hide().find("input").attr("ignore-data", 'true');

    var _div = contents.find("input[custInspFlag='C']").closest("table").closest("div");
    _div.each(function () {
        if ($(this).hasClass("span8")) {
            $(this).removeClass("span8").addClass("span4");
        }

        if ($(this).hasClass("span6")) {
            $(this).removeClass("span6").addClass("span3");
        }
    });

    contents.find('[name="decType"]').each(function () {
        if (this.id == 'radio_cust') {
            this.click();
            return;
        }

    });
}

function showAll(elements) {
    elements = elements || $(document.body);
    var contents = elements.contents();
    contents.find("td[class^='redtitleCss']").closest("div").show().find("input").attr("ignore-data", 'false');

    contents.find("td[class^='bluetitleCss']").closest("div").show().find("input").attr("ignore-data", 'false');

    contents.find("input[custInspFlag='C']").closest("td").show();
    contents.find("input[custInspFlag='I']").closest("td").show().closest("table").find("td:first").each(function () {
        if ($(this).attr("data-all")) {
            $(this).html(($(this).attr("data-all") || ""));
        }

    });

    var _div = contents.find("input[custInspFlag='I']").closest("table").closest("div");
    _div.each(function () {
        if ($(this).hasClass("span4")) {
            $(this).removeClass("span4").addClass("span8");
        }

        if ($(this).hasClass("span3")) {
            $(this).removeClass("span3").addClass("span6");
        }
    });

    contents.find('[name="decType"]').each(function () {
        if (this.id == 'radio_all') {
            this.click();
            return;
        }

    });
}


function fileDownload(value) {
    //定义一个form表单
    var form = $("<form>");
    form.attr("style", "display:none");
    form.attr("target", "");
    form.attr("method", "post");
    form.attr("action", $basePath + "/uploadfile/download?fileId=" + value);

    var input = $("<input>");
    input.attr("type", "hidden");
    input.attr("name", "exportData");
    input.attr("value", (new Date()).getMilliseconds());

    //将表单放置在web中
    $("body").append(form);
    form.append(input);
    form.submit();
}

function fastInput(callback) {
    var texts = $('form').find(":input:not(:radio),:disabled,:hidden");
    texts.each(function (i, ele) {
        if ($(this).hasClass('Wdate')) {
            $(this).bind("focus", function () {
                this.onclick();
                $dp.hide();
            });
        }

        $(ele).keydown(function (event) {
            if (13 == event.keyCode) {
                texts = $('form').find(":input:not([type='hidden'],:disabled,:hidden,:radio)");
                $(texts[(texts.index(ele) + 1) % texts.size()]).focus().select();
                if (texts.index(ele) === (texts.size() - 1) && typeof callback === "function") {
                    callback();
                }

                return;
            }
        });
    });
}


/**
 * 申报要素
 * @param cellvalue
 * @param options
 * @param rowObject
 * @returns {*}
 */
function decType(cellvalue, options, rowObject) {
    if (!cellvalue) {
        return "";
    }
    switch (cellvalue) {
        case '1':
            return "不限";
            break;
        case '2':
            return "只报关";
            break;
        case '3':
            return "只报检";
            break;
        case '4':
            return "关检一次申报";
            break;
        case '5':
            return "关检分别申报";
            break;
        default :
            "";
            break;
    }
}

/**
 * 自动计算数量、单价、总价
 * @param eleId 控件id
 * @param quantity 数量
 * @param price 单价
 * @param amount 总价
 */
function autoSum(eleId, params) {
    params = params || {
            quantityZ: {name: 'quantityZ', digit: 4},
            priceZ: {name: 'priceZ', digit: 4},
            amountZ: {name: 'amountZ', digit: 4}
        };

    var $quantity = $("#" + params.quantityZ.name).val();
    var $price = $("#" + params.priceZ.name).val();
    var $amount = $("#" + params.amountZ.name).val();

    if (eleId == params.quantityZ.name && $quantity != '') {
        if ($price != '') {
            $amount = $price * $quantity;
            $("#" + params.amountZ.name).val($amount.toFixed(params.amountZ.digit));
        } else if ($amount != '') {
            $price = $amount / $quantity;
            $("#" + params.priceZ.name).val($price.toFixed(params.priceZ.digit));
        }
    }

    if (eleId == params.priceZ.name && $price != '') {
        if ($quantity != '') {
            $amount = $price * $quantity;
            $("#" + params.amountZ.name).val($amount.toFixed(params.amountZ.digit));
        } else if ($amount != '') {
            $quantity = $amount / $price;
            $("#" + params.quantityZ.name).val($quantity.toFixed(params.quantityZ.digit));
        }
    }

    if (eleId == params.amountZ.name && $amount != '') {
        if ($quantity != '') {
            $price = $amount / $quantity;
            $("#" + params.priceZ.name).val($price.toFixed(params.priceZ.digit));
        } else if ($price != '') {
            $quantity = $amount / $price;
            $("#" + params.quantityZ.name).val($quantity.toFixed(params.quantityZ.digit));
        }
    }
}

/**
 * 成交方式变更后，针对不同的成交方式对运费保费做置灰控制
 * 1.进口：成交方式选CIF，运费、保费置灰
 * 2.出口：成交方式在FOB模式下，运费、保费置灰
 * @param flag 进出口标志 I进口，O出口
 */
function tradeTermsChange(flag, key, value, isInit) {
    if (flag == value) {

        var carriagesyC = $("[name='carriagesyC']").closest("div").find(":text,select");

        var insurancesyC = $("[name='insurancesyC']").closest("div").find(":text,select");

        // 运费置灰
        carriagesyC.attr("disabled", "disabled");
        // 保费置灰
        insurancesyC.attr("disabled", "disabled");

        if (!isInit) {
            carriagesyC.val("");
            insurancesyC.val("");
        }

    } else {
        if (!isInit) {
            $("[name='carriagesyC']").closest("div").find(":text,select,a").removeAttr("disabled");
            $("[name='insurancesyC']").closest("div").find(":text,select,a").removeAttr("disabled");
        }
    }
}

/**
 * 成交方式变更后，针对不同的成交方式对运费保费做置灰控制
 * 1.进口：成交方式选CIF，运费、保费置灰
 */
function tradeTermsForCIF(key, value) {
    tradeTermsChange('CIF', key, value);
}

/**
 * 成交方式变更后，针对不同的成交方式对运费保费做置灰控制
 * 1.出口：成交方式在FOB模式下，运费、保费置灰
 */
function tradeTermsForFOB(key, value) {
    tradeTermsChange('FOB', key, value);
}

/**
 * 同步操作(填写代理企业注册号，自动带入报检登记号)
 * @param ids 多个控件值需要同步的唯一id
 */
function asyncData(id1, id2) {
    $("input[name='" + id1 + "']").change(function () {
        if ($("input[name='" + id2 + "']").val() == '') {
            $("input[name='" + id2 + "']").val(this.value)
        }
    });

    $("input[name='" + id2 + "']").change(function () {
        if ($("input[name='" + id1 + "']").val() == '') {
            $("input[name='" + id1 + "']").val(this.value);
        }
    });
}

/**
 * 经营单位带出发货单位（填一样的）
 * @param key 经营单位的编号
 * @paran value 经营单位名称
 */
function asyncCompany(key, value) {
    $("#ownernaCxxxx").closest("div").find('input[autocomplete="off"]').data("text", key).val(key);

    $("#ownerco").val(key);
    $("#ownerna").val(value);
}

function upCustGoods(indx) {
    var layerIndx = layer.load(2, {shade: [0.2, '#000', true]});
    $.post($basePath + '/cargo/upCustGoods', {sheetNoZ: $("#worksheetindx").val(), indx: indx}).complete(function () {
        layer.close(layerIndx);
    }).success(function (msg) {
        if (msg == '') {
            layerAlertOk("上移成功", function () {
                location.reload();
            });
        } else {
            layerAlert(msg);
        }
    });
}
function upInspGoods(indx) {
    var layerIndx = layer.load(2, {shade: [0.2, '#000', true]});
    $.post($basePath + '/cargo/upInspGoods', {sheetNoZ: $("#worksheetindx").val(), indx: indx}).complete(function () {
        layer.close(layerIndx);
    }).success(function (msg) {
        if (msg == '') {
            layerAlertOk("上移成功", function () {
                location.reload();
            });
        } else {
            layerAlert(msg);
        }
    });
}
function downCustGoods(indx) {
    var layerIndx = layer.load(2, {shade: [0.2, '#000', true]});
    $.post($basePath + '/cargo/downCustGoods', {sheetNoZ: $("#worksheetindx").val(), indx: indx}).complete(function () {
        layer.close(layerIndx);
    }).success(function (msg) {
        if (msg == '') {
            layerAlertOk("下移成功", function () {
                location.reload();
            });
        } else {
            layerAlert(msg);
        }
    });
}
function downInspGoods(indx) {
    var layerIndx = layer.load(2, {shade: [0.2, '#000', true]});
    $.post($basePath + '/cargo/downInspGoods', {sheetNoZ: $("#worksheetindx").val(), indx: indx}).complete(function () {
        layer.close(layerIndx);
    }).success(function (msg) {
        if (msg == '') {
            layerAlertOk("下移成功", function () {
                location.reload();
            });
        } else {
            layerAlert(msg);
        }
    });
}

function lazyLoad(iframes) {
    for (var i = 0; i < iframes.length; i++) {
        var _callback = function (name, src) {

            return function (e) {
                var index = e.target.href.split("#tab")[1];
                if ($("#tab" + index + " iframe")[0]) {
                    return;
                }

                var _iframe = $('<iframe frameborder="0" style="width:100%;height: 100%;frameborder:0;border:0;"></iframe>');
                _iframe.attr("id", name);
                _iframe.attr("name", name);
                _iframe.attr("src", src);

                _iframe.appendTo("#tab" + index + " .responsive-table");
            }
        };

        $('a[data-toggle="tab"]:eq(' + i + ')').on('show', _callback(iframes[i].name, iframes[i].src));

    }
    $('a[data-toggle="tab"]:eq(0)').tab("show");
}

/**
 * 查询页面，必填的输入框校验和提示
 * @param arrayNames 属性名称
 * @returns {boolean} true or false
 */
function requiredQueryFields(arrayNames) {
    var $val;
    var titles = [];
    for (var name in arrayNames) {
        $val = $("[datafield='SearchTable." + arrayNames[name] + "']").val();
        if ($val) {
            return true;
        }

        titles.push($("[datafield='SearchTable." + arrayNames[name] + "']").closest("td").prev().text());
    }

    layer.alert(titles.toString() + "字段,请至少填写一个再进行查询！", {icon: 0, title: '提示信息', area: '450px'}, null);

    return false;
}

/**
 * 申报地海关组件变化，同步预录入编号 进口
 * @param key
 * @param value
 */
function onDeclarecustomscoCChangeI(key, value) {
    onPreentryidCChange("1");
}

/**
 * 申报地海关组件变化，同步预录入编号 出口
 * @param key
 * @param value
 */
function onDeclarecustomscoCChangeO(key, value) {
    onPreentryidCChange("0");
}

/**
 * 预录入编号18位，前9位可以设置默认值
 * （前4位按设置的默认关区显示，5-8位按当前年份显示，第9位出口为0，进口为1）
 * 后面9位人工录入，录入后带出海关编号，预录入编号填后九位可以申报但用户觉得不好统计(前九位不显示）
 * @param io 0-出口，1-进口
 */
function onPreentryidCChange(io) {
    // 海关预录入编号:前4位按设置的默认关区显示，5-8位按当前年份显示，第9位出口为0，进口为1
    var $pre = $("#declarecustomsco").val() + new Date().getFullYear() + io;
    var $preentryidC = $("#preentryid").val();

    // 海关预录入编号,在“非空”、“预录入编号长度为9位”、“并且生成的固定前缀也是9位”
    if ($preentryidC && $pre.length == 9) {
        if ($preentryidC.length == 9) {
            $("#preentryid").val($pre + $preentryidC);
        } else if ($preentryidC.length == 18 && $pre != $preentryidC.substring(0, 9)) {
            $("#preentryid").val($pre + $preentryidC.substring(9));
        }
    }
}

/**
 * 针对单一的综合输入框，检验规则筛选函数
 * @returns Z：综合规则，C：海关规则，I：检验检疫规则
 */
function zongToggle() {
    var custChecked = $("#cbox_cust", parent.document).is(':checked');
    var inspChecked = $("#cbox_insp", parent.document).is(':checked');
    if (custChecked && inspChecked) {
        return "Z";
    } else if (custChecked) {
        return "C";
    } else if (inspChecked) {
        return "I";
    } else {
        return "Z";
    }
}

/**
 * 针对单一的综合输入框，检验规则筛选函数
 * @returns Z：综合规则，C：海关规则，I：检验检疫规则
 */
function goodsZongToggle() {
    var custChecked = $("#radio_cust").is(':checked');
    var inspChecked = $("#radio_insp").is(':checked');
    var allChecked = $("#radio_all").is(':checked');
    if (allChecked) {
        return "Z";
    } else if (custChecked) {
        return "C";
    } else if (inspChecked) {
        return "I";
    } else {
        return "Z";
    }
}

function toggleCustInsp() {
    var custChecked = $("#cbox_cust").is(':checked');
    var inspChecked = $("#cbox_insp").is(':checked');

    if (custChecked && inspChecked) {
        $("#workSheet").contents().find("td[class^='redtitleCss']").closest("div").show();
        $("#workSheet").contents().find("td[class^='bluetitleCss']").closest("div").show();
    } else if (custChecked) {
        $("#workSheet").contents().find("td[class^='redtitleCss']").closest("div").show();
        $("#workSheet").contents().find("td[class^='bluetitleCss']").closest("div").hide();
    } else if (inspChecked) {
        $("#workSheet").contents().find("td[class^='redtitleCss']").closest("div").hide();
        $("#workSheet").contents().find("td[class^='bluetitleCss']").closest("div").show();
    } else {
        $("#workSheet").contents().find("td[class^='redtitleCss']").closest("div").hide();
        $("#workSheet").contents().find("td[class^='bluetitleCss']").closest("div").hide();
    }

    $("#workSheet").contents().find("div[class='span12 box-content']").each(function (i, ele) {
        var child_div = $(ele).children(":visible");
        var parent_div = $(ele).parent();
        if (child_div.length == 0 && parent_div.is(":visible")) {
            parent_div.hide();
        } else if (!parent_div.is(":visible")) {
            parent_div.show();
        }
    });
}

function initPage(indxZ, indxC, indxI) {
    // 初始化单独报关，单独报检的情况
    if (indxZ != "") {
        var iframesArray = {
            inspIframe: ["tab_title_5", "tab_title_6", "tab_title_7", "tab_title_8", "tab_title_9"],
            custIframe: ["tab_title_4"]
        }

        if (indxC == "") {
            $("#cbox_cust").removeAttr('checked');

            for (var i in iframesArray.custIframe) {
                $("#" + iframesArray.custIframe[i]).css('display', 'none');
            }
            toggleCustInsp();
        }

        if (indxI == "") {
            $("#cbox_insp").removeAttr('checked');

            for (var i in iframesArray.inspIframe) {
                $("#" + iframesArray.inspIframe[i]).css('display', 'none');
            }
            toggleCustInsp();
        }
    }
}

/**
 * 无纸化重新上传操作（只有在无纸化自动上传失败三次以后才可以触发）
 * @param btnId 控件按钮id
 * @param declNo 正式报检号
 */
function reupload(btnId, declNo, gridId) {
    $.ajax({
        type: 'post',
        url: $basePath + '/noPaperDec/reupload',
        dataType: 'json',
        data: {"declNo": declNo},
        success: function () {
            refreshNoPaperDecInfo();
            $("#" + btnId).attr("disabled", "disabled");

            // 重新载入
            $("#" + gridId).jqGrid('setGridParam', {
                url: $basePath + "/commonInsp/toAccessoryFileList",
                postData: {declNo: $("#declNo").val()},
                page: 1
            }).trigger("reloadGrid");
        },
        error: function () {
            layerAlert("无纸化上传操作失败，请检查无误后重新上传！")
        }
    });
}

function getNoPaperStatus() {
    var noPaperDecInfo;
    $.ajax({
        url: $basePath + '/noPaperDec/getNoPaperDecStatus',
        type: 'post',
        dataType: 'json',
        data: {"declNo": $("#declGetNo", parent.document).val()},
        async: false,
        success: function (data) {
            noPaperDecInfo = data;
        }
    });
    return noPaperDecInfo;
}
function blurEntBackup(id, customeCodeId, entType, custId, inspId) {

    var columns = ['组织机构代码', '关区代码', '关备案号', '检备案号']

    var width = "500px";

    var aaaa = $("#" + id).tautocomplete({
        relateKey: id, placeholder: "请输入关键字", width: width, columns: columns, regex: "^[a-zA-Z0-9\\s]+$", ajax: {
            url: $basePath + "/cache/blurEntBackup", dataType: "json", type: "post", data: function () {
                return {
                    featureClass: "P",
                    style: "full",
                    maxRows: 11,
                    customeCode: $("#" + customeCodeId).val(),
                    entType: entType,
                    name_startsWith: aaaa.searchdata()
                };
            }, success: function (jsonData) {
                var filterData = [];
                $.each(jsonData, function (i, item) {
                    var obj = {};
                    obj = {
                        id: item.ORGANIZATION_CODE + _split + item.CUSTOME_CODE + _split + item.BACKUP_NO_C + _split + item.BACKUP_NO_I,
                        ORGANIZATION_CODE: item.ORGANIZATION_CODE,
                        CUSTOME_CODE: item.CUSTOME_CODE,
                        BACKUP_NO_C: item.BACKUP_NO_C,
                        BACKUP_NO_I: item.BACKUP_NO_I
                    };
                    filterData.push(obj);
                });

                return filterData;
            }
        }, onchange: function () {
            var datas = aaaa.id().split(_split);

            var organization_code = datas[0] || '';
            var backup_no_c = datas[2] || '';
            var backup_no_i = datas[3] || '';

            $("#" + id).val(organization_code);
            $("#" + custId).val(backup_no_c);
            $("#" + inspId).val(backup_no_i);
            return;
        }
    });

    var displayTxt = $("#" + id).val();
    $("#" + id + "_input").data("text", displayTxt)
        .val(displayTxt);
}

//3-发送海关成功、4-发送海关失败、100-海关退单、599-其它扣留、600-待放行、800-实货放行。
function status(value, indx, rowObj) {
    if ('3' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-info">发送海关成功</span>';
    } else if ('4' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-success">发送海关失败</span>';
    } else if ('100' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-default">海关退单</span>';
    } else if ('599' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-primary">其它扣留</span>';
    } else if ('600' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">待放行</span>';
    } else if ('800' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">实货放行</span>';
    } else if ('0' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-success">已上报</span>';
    } else {
        if (null == rowObj['status']) {
           return "";
        } else {
           return '<span style="padding: 3px 3px" class="label label-warning">' + rowObj['status'] + '</span>';
        }
        return "";
    }
}


function statusInsp(value, indx, rowObj) {
    if ('01' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-info">已入库</span>';
    } else if ('02' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-success">入库失败</span>';
    } else if ('E1' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-success">本地暂存</span>';
    } else {
        if (null == rowObj['status']) {
            return "";
        } else {
            return '<span style="padding: 3px 3px" class="label label-warning">' + rowObj['status'] + '</span>';
        }
    }
}

function statusDeclInsp(value, indx, rowObj) {
    if ('1' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-info">电子审单通过</span>';
    } else if ('2' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-success">人工初审通过</span>';
    } else if ('3' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-default">查验</span>';
    } else if ('4' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-primary">单据放行</span>';
    } else if ('5' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">扣留</span>';
    } else if ('6' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">销毁</span>';
    } else if ('7' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">退单</span>';
    } else if ('8' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">放行</span>';
    } else if ('9' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">电子审单未通过</span>';
    } else if ('10' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">退运</span>';
    } else if ('10' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">已妥投</span>';
    } else if ('E1' == rowObj['status']) {
        return '<span style="padding: 3px 3px" class="label label-danger">本地暂存</span>';
    } else {
        if (null == rowObj['status']) {
            return "";
        } else {
            return '<span style="padding: 3px 3px" class="label label-warning">' + rowObj['status'] + '</span>';
        }
    }
}

function isOrNo(value, indx, rowObj) {
    if ('1' == value) {
        return '是';
    } else {
        return '否';
    }
}
